#pragma once
#include <iostream>
#include <string>
#include <queue>
#include <pthread.h>



template <class T>
class BlockQueue
{
private:
    bool isFull() { return _q.size() >= _cap; }
    bool isEmpty() { return _q.empty(); }
public:
    BlockQueue(int cap = 5)
        : _cap(cap),
          _csleep_num(0),
          _psleep_num(0)
    {
        pthread_mutex_init(&_mutex, nullptr);
        pthread_cond_init(&_full_cond, nullptr);
        pthread_cond_init(&_empty_cond, nullptr);
    }

    void Execute(const T &in)
    {
        pthread_mutex_lock(&_mutex);
        while(isFull())
        {
            _psleep_num++;
            std::cout << "生产者进入睡眠（等待）" << std::endl;
            pthread_cond_wait(&_full_cond, &_mutex);
            _psleep_num--;
        }

        _q.push(in);

        if(_csleep_num > 0)
        {
            pthread_cond_signal(&_empty_cond);
            std::cout << "一个消费者被唤醒" << std::endl;
        }

        pthread_mutex_unlock(&_mutex);
    }

    T Pop()
    {
        pthread_mutex_lock(&_mutex);

        while(isEmpty())
        {
            _csleep_num++;
            std::cout << "消费者进入睡眠（等待）" << std::endl;
            pthread_cond_wait(&_empty_cond, &_mutex);
            _csleep_num--;
        }

        T ret = _q.front();
        _q.pop();
        if(_psleep_num > 0)
        {
            pthread_cond_signal(&_full_cond);
            std::cout << "一个生产者被唤醒" << std::endl;
        }

        pthread_mutex_unlock(&_mutex);
        return ret;
    }

    ~BlockQueue()
    {
        pthread_mutex_destroy(&_mutex);
        pthread_cond_destroy(&_full_cond);
        pthread_cond_destroy(&_empty_cond);
    }

private:
    std::queue<T> _q;
    int _cap;

    pthread_mutex_t _mutwex;
    pthread_cond_t _full_cond;
    pthread_cond_t _empty_cond;

    int _csleep_num; // 消费者睡眠的数量
    int _psleep_num; // 生产者睡眠的数量
};